import { usePreferencesStore } from './index'
import type {
  PreferencesState,
  CurrentLangeuage,
  BrowserLanguageList
} from './types'

export const PREFERENCES_KEY = 'PREFERENCES_KEY'

export const baseTheme = 'light'

export const baseThemeColors = {
  primary: '0, 107, 229',
  error: '255, 56, 96',
  success: '87, 209, 136',
  warning: '239, 189, 72',
  info: '144, 147, 153'
}

const baseLanguage = 'zh_CN'

export const basePreferences: PreferencesState = {
  appearance: {
    theme: {
      theme: baseTheme,
      currentTheme: baseTheme,
      themeColors: { ...baseThemeColors }
    }
  },
  general: {
    lang: {
      language: baseLanguage,
      currentLangeuage: baseLanguage,
      languageList: [
        { name: 'language.auto', value: 'auto' },
        { name: 'language.zh', value: 'zh_CN' },
        { name: 'language.zh-tw', value: 'zh_TW' },
        { name: 'language.en', value: 'en_US' }
      ]
    }
  }
}

export const systemTheme = window.matchMedia('(prefers-color-scheme: dark)')

export const getSystemTheme = () => {
  return systemTheme.matches ? 'dark' : 'light'
}

const handleSystemThemeChange = () => {
  const preferencesStore = usePreferencesStore()
  preferencesStore.setTheme('system')
}

export const startThemeChangeListener = () => {
  systemTheme.addEventListener('change', handleSystemThemeChange)
}

export const stopThemeChangeListener = () => {
  systemTheme.removeEventListener('change', handleSystemThemeChange)
}

export const browserLanguageList: BrowserLanguageList = {
  'zh-CN': 'zh_CN',
  'zh-TW': 'zh_TW',
  'en-US': 'en_US'
}

export const getBrowserLanguage = (): CurrentLangeuage => {
  const language = navigator.language
  return browserLanguageList[language] || baseLanguage
}
